import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import request from '@/services/request';
import type { ResponseData } from '@/services/types';

interface MetricItem {
  id: number;
  name: string;
  value: number;
  unit: string;
  trend: number;
}

interface MetricsResponse {
  list: MetricItem[];
}

interface MetricsState {
  metrics: MetricItem[];
  loading: boolean;
  error: string | null;
  fetchMetrics: () => Promise<void>;
  updateMetric: (id: number, value: number) => void;
}

export const useMetricsStore = create<MetricsState>()(
  persist(
    (set) => ({
      metrics: [],
      loading: false,
      error: null,

      fetchMetrics: async () => {
        set({ loading: true, error: null });
        try {
          const result = await request.get<ResponseData<MetricsResponse>>('/metrics/list');
          if (result.code === 0) {
            set({ metrics: result.data.list });
          } else {
            set({ error: result.message || '获取度量指标失败' });
          }
        } catch (error) {
          console.error('获取度量指标失败:', error);
          set({ error: '获取度量指标失败' });
        } finally {
          set({ loading: false });
        }
      },

      updateMetric: (id: number, value: number) => {
        set((state) => ({
          metrics: state.metrics.map((metric) =>
            metric.id === id ? { ...metric, value } : metric
          ),
        }));
      },
    }),
    {
      name: 'metrics-storage', // 存储的 key
      partialize: (state) => ({ metrics: state.metrics }), // 只持久化 metrics 数据
    }
  )
); 